<template>
  <div class="box">
    <myDivider name="生成巡查码"></myDivider>
    <el-page-header @back="$router.go(-1)"></el-page-header>
    <div style="margin-top: 50px;margin-left: 70px;">

      <!-- 顶部form -->
      <el-form :model="topForm" :rules="topFormRules" ref="topForm" label-width="120px">
        <el-form-item label="巡查类别：">
          <span>{{ topForm.categoryName }}</span>
        </el-form-item>
        <div style="display: flex;">
          <el-form-item label="所属小区：" prop="residentialName">
            <div style="position: relative;">
              <div @click="openPop('选择小区')"
                style="width: 400px;height: 100%;position: absolute;left: 0;top: 0;z-index: 10;cursor: pointer;">
              </div>
              <el-input style="width: 400px;" v-model="topForm.residentialName" clearable
                placeholder="请选择小区"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="类别负责人：" prop="lbfzr">
            <div style="position: relative;">
              <div @click="openPop('选择负责人')"
                style="width: 400px;height: 100%;position: absolute;left: 0;top: 0;z-index: 10;cursor: pointer;">
              </div>
              <el-select style="width: 400px;" v-model="topForm.lbfzr" multiple collapse-tags placeholder="请选择负责人">
                <el-option v-for="item, i in lbfzrData" :key="i" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </el-form-item>
        </div>
      </el-form>

      <!-- 卡片form -->
      <div @click="cardClick(i)" v-for="item, i in cardForm" :key="i" style="margin-top: 20px;width: 530px;">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>巡查码{{ i + 1 }}</span>
            <el-button v-if="cardForm.length > 1" @click="deleteCard(i)" style="float: right; padding: 3px 0;color:red"
              type="text">删除</el-button>
          </div>
          <el-form :model="item" ref="cardForm" :rules="cardFormRules" label-width="100px">

            <el-form-item label="名称：" prop="codeName">
              <el-input style="width: 250px;" v-model="item.codeName" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="位置：" prop="latLon">
              <div style="display: flex;">
                <div style="position: relative;">
                  <div style="width: 250px;height: 100%;position: absolute;left: 0;top: 0;z-index: 10;"></div>
                  <el-input  type="textarea"
                  :rows="2" style="width: 250px;" v-model="item.positionName" placeholder="请选择位置"></el-input>
                </div>
                <span style="color: #4ca1e7;cursor: pointer;margin-left: 10px;" @click="goLatLon(item)">点击获取经纬度</span>
              </div>
            </el-form-item>
            <el-form-item label="位置参照图：">
              <myuploadByCHGLImg v-if="myuploadByCHGLImgShow" :canUploadNum="1" :id="uploadId" ref="byimg" @getImgList="getImgList"
                uploadUrl="/business/patrolQRCode/uploadImg" deleteUrl="/business/patrolQRCode/deleteImg">
              </myuploadByCHGLImg>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <el-button type="success" style="margin-top: 20px;" @click="addCard">添加巡查码</el-button>
    </div>


    <!-- 底部按钮 -->
    <div class="footer">
      <div>
        <el-button style="width: 100px;" type="info" @click="cancellation">取消</el-button>
        <el-button style="width: 100px;" type="primary" @click="save">保存</el-button>
      </div>
    </div>

    <!-- 弹窗 -->
    <!-- 地图弹窗 -->
    <el-dialog title="选择位置" :visible.sync="mapPopShow" width="80%">
      <div class="mapStyle" id="map" v-if="mapPopShow">
        <span style="display: block;margin-bottom: 15px;font-size: 20px;font-weight: 600">{{'选择的位置：'+positionName}}</span>
        <div id="container">
          <div class="keyAddressStyle">
            <el-input placeholder="省/市/区" v-model="keyAddress">
              <el-button slot="append" icon="el-icon-search" @click="addressChange"></el-button>
            </el-input>
          </div>
        </div>

      </div>
    </el-dialog>


    <!-- 选择小区弹窗 -->
    <el-dialog :close-on-click-modal="false" title="选择小区" :visible.sync="residentialPopShow" width="50%"
      class="residentialPopStyle">

      <div>
        <el-input v-model="residentialPopKey1" style="width: 250px;" placeholder="社区名称"></el-input>
        <el-button style="margin-left: 15px" type="primary" @click="popSouSuo">查询</el-button>
        <el-button style="margin-left: 15px" @click="popReset">重置</el-button>
      </div>
      <div class="listStyle">
        <div v-for="item, i in residentialPopData"
          style="width: 20%;margin: 10px 0;overflow: hidden;padding: 0 10px;box-sizing: border-box;" :key="i">
          <el-tooltip class="item" effect="dark" :content="item.residentialInfo" placement="top-start">
            <el-radio style="width: 100%;" v-model="residentialPopRadio" :label="item.residentialId">{{ item.name
              }}</el-radio>
          </el-tooltip>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popClose">取 消</el-button>
        <el-button type="primary" @click="popOk">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 选择负责人弹窗 -->
    <el-dialog :close-on-press-escape="false" :show-close="false" :close-on-click-modal="false" title="选择负责人"
      :visible.sync="headPopShow" width="50%" class="residentialPopStyle">

      <div style="display: flex;justify-content: space-between;align-items: center;">
        <div>
          <el-input v-model="headPopKey1" style="width: 250px;" placeholder="用户姓名"></el-input>
          <el-button style="margin-left: 15px" type="primary" @click="popSouSuo">查询</el-button>
          <el-button style="margin-left: 15px" @click="popReset">重置</el-button>
        </div>
        <el-button style="margin-left: 100px" type="danger" plain @click="empty">全部清空</el-button>
      </div>

      <div class="listStyle">

        <div v-for="item, i in headPopData"
          style="width: 20%;margin: 10px 0;overflow: hidden;padding: 0 10px;box-sizing: border-box;" :key="i">
          <el-tooltip class="item" effect="dark" :content="item.result" placement="top-start">
            <el-checkbox @change="checkBoxChange(item)" v-model="item.checked">{{
              item.name
            }}</el-checkbox>
          </el-tooltip>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popClose">取 消</el-button>
        <el-button type="primary" @click="popOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui';
import myuploadByCHGLImg from '@/components/upload/myuploadByCHGLImg';
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  securityJsCode: "74a9bc741a93c4984284167952f22f4a",//安全密钥
};
export default {
  components: {
    myuploadByCHGLImg
  },
  data() {
    var validator1 = (rule, value, callback) => {
      // value 验重
      //对服务器验重....
      //  对目前起的名称验重
      let a = 0
      this.cardForm.forEach(el => {
        if (el.codeName == value) {
          a++
        }
      })
      if (a > 1) {
        callback(new Error('名称重复'));
      }
      callback()
    }
    return {
      myuploadByCHGLImgShow:false,

      positionName:'',
      topForm: {},
      topFormRules: {
        residentialName: [{ required: true, message: '请选择所属小区', trigger: 'change' },],
        lbfzr: [{ required: true, message: '请选择类别负责人', trigger: 'change' },],
      },
      lbfzrData: [],//类别负责人数据

      cardForm: [{ codeName: '', latLon: '', positionUrl: '', }],
      cardFormRules: {
        codeName: [{ required: true, message: '请输入名称', trigger: 'blur' },
        { validator: validator1, trigger: 'blur' }
        ],
        latLon: [{ required: true, message: '请选择位置', trigger: 'change' },],
      },
      // 弹窗相关==============================================
      popType: '',
      // 选择小区弹窗 ==============
      residentialPopShow: false,
      residentialPopKey1: '',
      residentialPopData: [],
      residentialPopRadio: '',
      // 选择负责人弹窗 ==============
      headPopShow: false,
      headPopKey1: '',
      headPopData: [],
      headPopCache: [],//缓存  

      activeIndex: null, //当前点击的card
      mapPopShow: false,
      uploadId: 0,
      keyAddress: '',
      map: null,
      marker: null,
      geocoder: null,//编码
      AMap: null,
      logOnUser: {},
    }
  },
  activated() {
    this.myuploadByCHGLImgShow = false
    setTimeout(()=>{
      this.myuploadByCHGLImgShow = true
    },50)


    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.$set(this.topForm, 'categoryName', this.$route.query.categoryName)
    this.$set(this.topForm, 'residentialName', '')
    this.$set(this.topForm, 'residentialId', '')
    this.$set(this.topForm, 'lbfzr', []) //选择负责人回显数组
    this.$set(this.topForm, 'categoryResponsibleIds', []) //选中负责人后端需要传的id数组
    this.cardForm = [{ codeName: '', latLon: '', positionUrl: '', }]
    // 获取负责人下拉框数据
    this.getHeadSelectData()
    this.$nextTick(() => {
      this.$refs.topForm.clearValidate()
      this.$refs['cardForm'][0].clearValidate()
    })
  },
  methods: {

    empty() {  //选择负责人全部取消按钮
      this.headPopData.forEach(el => {
        el.checked = false
      })
      this.headPopCache = []
    },
    checkBoxChange(item) {
      if (item.checked) { //增加
        this.headPopCache.push(item.id)
      } else {//去除
        this.headPopCache.forEach((el, i) => {
          if (el == item.id) {
            this.headPopCache.splice(i, 1)
          }
        })
      }
    },
    async getResidentialPopTableData() { //获取选择小区弹窗数据
      let res = await this.$api.patrol.myPatrolGetCommunityList(this.residentialPopKey1)
      if (res.code == 200) {
        this.residentialPopData = res.data
      } else {
        this.$message.error(res.message)
      }
    },

    async getHeadPopTableData() {//获取选择负责人弹窗数据
      let res = await this.$api.patrol.myGetStaffList({
        "unitType": this.logOnUser.unitType, //company、agency
        "unitId": this.logOnUser.unitId,
        "name": this.headPopKey1
      })
      if (res.code == 200) {
        res.data.forEach(el => { //先统一设为未选中
          el.checked = false
        })
        this.headPopData = res.data
        this.headPopData.forEach(el => {
          this.headPopCache.forEach(ell => {
            if (el.id == ell) {
              el.checked = true
            }
          }
          )
        })
      } else {
        this.$message.error(res.message)
      }
    },
    async getHeadSelectData() {//获取选择负责人下拉框数据
      let res = await this.$api.patrol.myGetStaffList({
        "unitType": this.logOnUser.unitType, //company、agency
        "unitId": this.logOnUser.unitId,
        "name": ''
      })
      if (res.code == 200) {
        this.lbfzrData = res.data
      } else {
        this.$message.error(res.message)
      }

    },
    openPop(name) { //打开弹窗
      this.popType = name
      switch (name) {
        case '选择小区':
          this.residentialPopShow = true
          this.residentialPopRadio = this.topForm.residentialId
          break;
        case '选择负责人':
          this.headPopShow = true
          this.headPopCache = JSON.parse(JSON.stringify(this.topForm.categoryResponsibleIds))
          break
      }
      this.popReset()
    },
    popSouSuo() {//弹窗搜索
      switch (this.popType) {
        case '选择小区':
          this.getResidentialPopTableData()
          break;
        case '选择负责人':
          this.getHeadPopTableData()
          break
      }
    },
    popReset() {//弹窗搜索条件重置
      switch (this.popType) {
        case '选择小区':
          this.residentialPopKey1 = ''
          this.getResidentialPopTableData()
          break;
        case '选择负责人':
          this.headPopKey1 = ''
          this.getHeadPopTableData()
          break
      }
    },


    popOk() {
      switch (this.popType) { //弹窗点确定
        case '选择小区':
          if (!this.residentialPopRadio) {
            this.$message.error('请选择小区')
            return
          }
          this.residentialPopData.forEach(el => {
            if (el.residentialId == this.residentialPopRadio) {
              this.$set(this.topForm, 'residentialName', el.name) //赋值名字
            }
          })
          this.$set(this.topForm, 'residentialId', this.residentialPopRadio) //赋值id
          console.log('选中的小区', this.topForm.residentialId);
          this.residentialPopShow = false
          break;
        case '选择负责人':
          if (this.headPopCache.length == 0) {
            this.$message.error('您未选择负责人')
            return
          }
          this.topForm.categoryResponsibleIds = this.headPopCache

          let arr = []
          this.lbfzrData.forEach((el, i) => {
            this.topForm.categoryResponsibleIds.forEach(ell => {
              if (el.id == ell) {
                arr.push(el.name)
              }
            })
          })
          this.$set(this.topForm, 'lbfzr', arr) //选择负责人回显数组
          console.log('选中的负责人', this.topForm.lbfzr);
          this.headPopShow = false
          break
      }
    },
    popClose() { //弹窗点取消
      switch (this.popType) {
        case '选择小区':
          this.residentialPopShow = false
          break;
        case '选择负责人':
          this.headPopShow = false

          break
      }
    },
    cardClick(index) { //点击图片 ，获取它的index
      this.activeIndex = index
    },
    getImgList(val) {

      if (val.length == 0) {
        this.cardForm[this.activeIndex].positionUrl = ''
      } else {
        this.cardForm[this.activeIndex].positionUrl = val[0]
      }
    },
    goLatLon(item) {
      this.mapPopShow = true
      this.keyAddress = ''

      this.$nextTick(() => {
        let loadingInstance = this.$loading({
          target: document.getElementById('map')
        })
        AMapLoader.load({
          key: "b59ffa4664995330f554d4aedc02b03c", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
          .then((AMap) => {
            this.AMap = AMap

            let mylatlot;
            let myZoom;
            if (item.latLon) { // 如果有经纬度，就用经纬度来设为中心，没有就默认
              mylatlot = item.latLon.split(',')
              myZoom = 15
              this.positionName = item.positionName
            } else {
              mylatlot = [116.397428, 39.90923]
              myZoom = 11
              this.positionName = ''
            }

            this.map = new AMap.Map("container", {
              // viewMode: "3D", // 是否为3D地图模式
              zoom: myZoom, // 初始化地图级别
              center: mylatlot, // 初始化地图中心点位置
            });


            this.map.on('complete', () => { //地图加载完毕函数
              this.geocoder = new this.AMap.Geocoder()
              loadingInstance.close();
              if (item.latLon) { //如果有经纬度，添加点标
                this.marker = new this.AMap.Marker({ //创建点标点
                  position: mylatlot,
                });
                this.map.add(this.marker);    //添加点标点
              }

              this.map.on("click", (ev) => { //地图点击增加点标，获取位置
                if (this.marker != null) {  //如果之前有点标点那去除
                  this.marker.remove()
                }
                let { lng, lat } = ev.lnglat;   //获取到的经纬度
                this.marker = new this.AMap.Marker({ //创建点标点
                  position: [lng, lat],
                });
                this.cardForm[this.activeIndex].latLon = `${lng},${lat}`

                this.map.add(this.marker);    //添加点标点
                this.geocoder.getAddress([lng, lat], (status, result) => { //获取点击的位置
                  console.log(status, result);
                  if (status === 'complete' && result.info === 'OK') {
                    console.log(result.regeocode.formattedAddress,'详细位置');
                    this.positionName = result.regeocode.formattedAddress
                    this.cardForm[this.activeIndex].positionName =result.regeocode.formattedAddress
                  }
                })
              });
            });
          })
          .catch((e) => {
            console.log(e);
          });


      })
    },
    addressChange() {
      this.geocoder.getLocation(this.keyAddress, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          console.log(result.geocodes[0].location);
          let lng = result.geocodes[0].location.lng
          let lat = result.geocodes[0].location.lat
          this.map.setCenter([lng, lat], true)
          this.map.setZoom(16)
        }
      })
    },
    addCard() {
      this.cardForm.push({ codeName: '', latLon: '', positionUrl: '', })
    },
    deleteCard(index) {
      this.$confirm('是否删除该巡查码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cardForm.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {

      });

    },
    cancellation() {
      this.$confirm('取消后内容不保存，确定取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {

      });
    },
    save() {

      let qualifiedNum = 0
      this.cardForm.forEach((el, i) => {
        this.$refs['cardForm'][i].validate((valid) => {
          if (valid) {
            qualifiedNum++
          } else {
            return false;
          }
        });
      })
      this.$refs['topForm'].validate((valid) => {
        if (valid) {
          if (qualifiedNum == this.cardForm.length) { //验证通过

            this.$confirm('请检查无误后提交?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let arr = []
              this.cardForm.forEach(el => {
                arr.push({
                  "categoryId": this.$route.query.id, //巡查码类别id 必填
                  "residentialId": this.topForm.residentialId, //所属小区id  必填
                  "categoryResponsibleIds": JSON.stringify(this.topForm.categoryResponsibleIds), //扫码权限人id  必填
                  "codeName": el.codeName, //名称 必填
                  "longitude": el.latLon.split(',')[0], //经度
                  "latitude": el.latLon.split(',')[1], //纬度
                  "positionUrl": el.positionUrl,
                  positionName:el.positionName
                })
              })
              console.log(arr, '最终数据');
              let res = await this.$api.patrol.myPatrolQRCodeInsert(arr)
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.$router.push('/PatrolQRcodeList')
              } else {
                this.$message.error(res.message)
              }

            }).catch(() => {

            });

          }
        } else {
          return false;
        }
      });

    },

  }
}
</script>

<style lang="less" scoped>
.residentialPopStyle {
  .listStyle {
    display: flex;
    flex-wrap: wrap;
    height: 200px;
    overflow-y: scroll;
    margin-top: 50px;

    &::-webkit-scrollbar {
      width: 2px !important;

      &-thumb {
        background-color: rgb(45, 180, 234);
      }
    }
  }
}

.mapStyle {
  height: 65vh;
  width: 100%;
  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 90%;
    position: relative;
  }

  .keyAddressStyle {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 250px;
    height: 30px;
    z-index: 100;
  }
}

.stepStyle {
  display: flex;
  justify-content: space-between;
  width: 433px;
  margin: auto;

  .stepElStyle {
    cursor: pointer;
    width: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;

    >div {
      width: 30px;
      height: 30px;
      border-radius: 100px;
      // background-color: #4095e5;
      border: 1px solid black;
      display: flex;
      justify-content: center;
      align-items: center;

      >span {
        color: rgb(0, 0, 0);

      }
    }

    >span {
      margin-top: 5px;
    }

    &.active {
      >div {

        background-color: #4095e5;
        border: 1px solid #4095e5;

        >span {
          color: rgb(255, 255, 255);

        }
      }
    }
  }
}

.footer {
  position: fixed;
  bottom: 10px;
  left: 50%;

}
</style>